<?php

namespace App\Models\Admin;

use App\Common\ValidateHandler;
use App\Models\BaseModel;
use App\Models\Admin\Rule;
use App\Models\Admin\Role;
use Auth;

class Menu extends BaseModel
{
    protected $fillable = [
        'id', 'pid', 'title', 'url', 'icon',
        'level', 'sort', 'next', 'created_at', 'updated_at'
    ];

    public function getList($pageSize)
    {
        $data = $this->orderBy('next', 'asc')->orderBy('level', 'asc')->orderBy('sort', 'desc')->paginate($pageSize)->toArray();
        return $this->success($data);
    }

    public function getUserMenuNode()
    {
        $user = Auth::guard('admin')->user();
        $userRole = Role::find($user->role_id);
        $menuStr = $userRole->half_menu_ids.$userRole->menu_ids;
        $menuIds = explode(',', $menuStr);
        $menuIds = array_filter($menuIds);
        if ($user->id == 1) {
            $menus = $this->orderBy('next', 'asc')->orderBy('level', 'asc')->orderBy('sort', 'desc')->get()->toArray();
        } else {
            $menus = $this->whereIn('id', $menuIds)->orderBy('next', 'asc')->orderBy('level', 'asc')->orderBy('sort', 'desc')->get()->toArray();
        }

        $arr = [];
        foreach ($menus as $key => $menu) {
            $item = [];
            $item['id'] = $menu['id'];
            $item['pid'] = $menu['pid'];
            $item['title'] = $menu['title'];
            $item['url'] = $menu['url'];
            $item['icon'] = $menu['icon'];
            $item['children'] = []; //子节点

            if ($menu['level'] == 0) {
                // 主节点 直接push到arr中
                $arr['m-'.$menu['id']] = $item;
            } else {
                // 从节点 push到clild中
                array_push($arr['m-'.$menu['pid']]['children'], $item);
            }
        }

        return $this->success(['menus' => $arr]);
    }

    public function handle($data)
    {
        $result = $this->validate($data);
        if (!$result['res']) {
            return $this->error($result);
        }

        $data['level'] = $data['pid'] == 0 ? 0 : 1;
        $data['next'] = $data['pid'] == 0 ? 0 : $data['pid'];
        if ($data['id'] == 'new') {
            unset($data['id']);
            $res = $this->create($data);
            if ($res->pid == 0) {
                //主标签next写id值
                $this->where('id', $res->id)->update(['next' => $res->id]);
            }
        } else {
            $data['next'] = $data['pid'] == 0 ? $data['id'] : $data['pid'];
            $whereArr = ['id' => $data['id']];
            $id = $data['id'];
            // 一级菜单如果存在子菜单不允许更改为二级菜单
            $c = $this->where('pid', $id)->count();
            if ($c>0 && $data['pid']!=0) {
                return $this->error(['info'=>'此标签存在子标签，不允许更换菜单等级']);
            }
            $this->where('id', $id)->update($data);
        }

        return $this->success(['info' => '操作成功']);
    }

    private function validate($data)
    {
        $arr = [
            0 => [
                'name' => '菜单名称',
                'value' => $data['title'],
                'func' => 'is_empty'
            ],
            1 => [
                'name' => '排序比重',
                'value' => $data['sort'],
                'func' => 'length_limit',
                'min' => 1,
                'max' => 2
            ]
        ];
        if ($data['pid'] != 0) {
            //二次菜单地址不能为空
            $arr[2] = [
                'name' => '二级菜单地址',
                'value' => $data['url'],
                'func' => 'is_empty'
            ];
        }
        return ValidateHandler::do($arr);
    }

    public function getFirstMenu()
    {
        $data = $this->where('level', 0)->select(['id', 'title'])->get()->toArray();
        array_unshift($data, ['id' => 0, 'title' => '无主菜单']);

        return $this->success($data);
    }

    public function getSecondMenu($pid)
    {
        $data = $this->where('pid', $pid)->where('level', 1)->select(['id', 'title'])->get()->toArray();
        if (count($data) == 0) array_unshift($data, ['id' => 0, 'title' => '此主菜单没有子菜单','pid'=>$pid]);

        return $this->success($data);
    }

    public function deleteAction($id)
    {
        $menu = $this->where('id', $id)->first();
        if ($menu->level == 0) {
            $c = $this->where('pid', $id)->count();
            if ($c > 0) {
                return $this->error(['info' => '此标签存在子标签，不可删除']);
            }
        }

        // 菜单被权限选中不可删除
        $ruleCount = Rule::where('menu_id', $id)->count();
        if ($ruleCount > 0) {
            return $this->error(['info' => '请删除此菜单对应的权限后再来删除']);
        }

        // 菜单被角色选中不可删除
        $roleCount = Role::where("menu_ids", "like", "%$id,%")
                          ->orWhere("menu_ids", "like", "%,$id,%")
                          ->orWhere("half_menu_ids", "like", "$id,%")
                          ->orWhere("half_menu_ids", "like", "%,$id,%")
                          ->count();
        if ($roleCount > 0) {
            return $this->error(['info' => '请删除此菜单对应的角色后再来删除']);
        }

        $this->where('id', $id)->delete();
        return $this->success(['info' => '操作成功']);
    }
}
